'use strict'

const client = require('prom-client')
const os = require('os')
const util = require('util')
const exec = util.promisify(require('child_process').exec)
const plot = require('./plot_log_parser')

const run = async function () {
  const Registry = client.Registry
  const register = new Registry()
  const gateway = new client.Pushgateway('http://admin.pocplus.com:9991', [], register)
  const prefix = 'chia_plots'

  const hostname = os.hostname().split('.').shift()
  // Add a default label which is added to all metrics
  register.setDefaultLabels({
    app: hostname,
  })
  // Enable the collection of default metrics
  client.collectDefaultMetrics({ register })
  // const test = new client.Counter({
  //   name: `${prefix}`,
  //   help: `${prefix}_test`,
  //   registers: [register],
  // })
  // register.registerMetric(test)
  // test.inc(10)Number of processes

  // gauge.set(10); // Set to 10
  // gauge.inc(); // Increment 1
  // gauge.inc(10); // Increment 10
  // gauge.dec(); // Decrement by 1
  // gauge.dec(10); // Decrement by 10
  try {
    const cmdline =
      os.platform() == 'win32'
        ? 'WMIC path win32_process get Caption,Processid,Commandline'
        : 'ps -ef'
    const result = await exec(cmdline)
    const stdout = result.stdout
    // console.log(stdout)
    const processes = new client.Gauge({
      name: `${prefix}_number_of_processes`,
      help: `${prefix}_number_of_processes_help`,
    })
    const process = []
    const filter = os.platform() == 'win32' ? 'mon\\chia' : 'chia plots'
    stdout.split(/\r?\n/).forEach(function (line) {
      if (line.indexOf(filter) > -1) {
        // console.log(line)
        process.push(line)
      }
    })
    processes.set(process.length)
    register.registerMetric(processes)
  } catch (e) {}

  // 'id',
  // 'start',
  // 'plot_size',
  // 'buffer_size',
  // 'buckets',
  // 'threads',

  if (process.argv.length > 2) {
    const arr = plot.parser_log(process.argv[2], !!process.argv[3])
    const running = new client.Gauge({
      name: `${prefix}_running`,
      help: `${prefix}_running_help`,
      labelNames: ['id', 'start', 'plot_size', 'buffer_size', 'buckets', 'threads'],
    })
    register.registerMetric(running)

    const complete = new client.Gauge({
      name: `${prefix}_complete`,
      help: `${prefix}_complete_help`,
      labelNames: [
        'id',
        'start',
        'plot_size',
        'buffer_size',
        'buckets',
        'threads',
        'phase1',
        'phase2',
        'phase3',
        'phase4',
        'copy_time',
        'total_time',
        'file',
        'temporary',
        'file_size',
        'progress'
      ],
    })

    
    register.registerMetric(complete)
    arr.forEach((elem) => {
      // console.log(elem);
      if (elem.progress < 100) {
        const e = {
          id: elem.id,
          start: elem.start,
          plot_size: elem.plot_size,
          buffer_size: elem.buffer_size,
          buckets: elem.buckets,
          threads: elem.threads,
        }
        if (e.id) {
          const progress = elem.progress
          running.set(e, progress)
        }
      }else{
        const total_time = elem.total_time
        complete.set(elem, total_time)
      }
    })
  }

  if (process.argv.length > 3) {
    console.log(await register.metrics())
  } else {
    gateway.push({ jobName: prefix }, (err, resp, body) => {
      console.log(`Error: ${err}`)
      console.log(`Body: ${body}`)
      console.log(`Response status: ${resp.statusCode}`)
    })
  }
}

run()
